/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.support.custom.binding;

/**
 *
 * @author renan_luz
 */
import com.lavantech.gui.comp.DateTimePicker;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.GregorianCalendar;
import javax.swing.JComponent;
import org.springframework.binding.form.FormModel;
import org.springframework.richclient.form.binding.support.CustomBinding;

public class TimePickerBinding extends CustomBinding implements PropertyChangeListener {

    private final DateTimePicker timePicker;
    private final boolean readOnly;
    private boolean isSettingText;

    public TimePickerBinding(FormModel formModel, String formPropertyPath, DateTimePicker timePicker, boolean readOnly) {
        super(formModel, formPropertyPath, GregorianCalendar.class);
        this.timePicker = timePicker;
        this.readOnly = readOnly;
    }

    @Override
    protected void valueModelChanged(Object newValue) {
        isSettingText = true;
        setTimePickerValue((GregorianCalendar) newValue);
    }

    private void setTimePickerValue(GregorianCalendar calendar) {
        if (calendar == null) {
            timePicker.setCalendar(null);
        } else {
            timePicker.setCalendar(calendar);
        }
    }

    @Override
    protected JComponent doBindControl() {
        setTimePickerValue((GregorianCalendar) getValue());
        timePicker.getEditor().addPropertyChangeListener("value", this);
        return timePicker;
    }

    public void propertyChange(PropertyChangeEvent evt) {
        if (!isSettingText && !isReadOnly()) {
            controlValueChanged(timePicker.getCalendar());
        }
    }

    @Override
    protected void readOnlyChanged() {
        timePicker.setEditable(isEnabled() && !this.readOnly && !isReadOnly());
    }

    @Override
    protected void enabledChanged() {
        timePicker.setEnabled(isEnabled()); 
        readOnlyChanged();
    }
}  
